<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Slider extends Admin_Controller {

	var $model = "mslider";
	var $view = "slider";
	var $resource_admin = 'RESOURCE/static/';

	function __construct() {
        parent::__construct();
        $this->load->helper('util_helper');
        $this->load->model($this->model);
        $this->load->library('SimpleImage');
        $this->url_index = admin_url().$this->view;
        $this->url_edit = $this->url_index.'/edit/';
        $this->url_delete = $this->url_index.'/delete/';
        $this->url_search = $this->url_index.'/search/';
    }

	public function index($page = 0)
	{	
		$data = array();
		// paging
        $config = array();
        $p= $this->uri->segment(4, 0);
        $page = (int)substr(strrchr($p, "-"), 1); //substr($p, -1);
        $page = ($page <= 0) ? 1 : $page;
        $config['per_page'] = 10;
        $config['cur_page'] = $page;
        $config['base_url'] = $this->url_index.'/index/';

        $config['total_rows'] = $this->{$this->model}->num();
        $this->pagination->initialize($config);
		$this->db->order_by('slider.sli_id desc');
        $data['sliders'] = $this->{$this->model}->pagination('','',$config);

		$this->template_data['main'] = 'admin/slider/index';
		$this->template->load('layout/admin/layout',$this->template_data,$data);
	}

	public function edit($editID = 0)
	{
        $post = $this->input->post();

        if ($editID == null || $editID == 0)
        {
            $editID = $this->{$this->model}->insert(array('sli_createtime' =>time()));
            redirect(admin_url(). 'slider/edit/'. $editID);
        }// endif

        if($editID > 0){
            $data['edit'] = $this->{$this->model}->get($editID);
            if(!$data['edit'])  redirect($this->url_edit.'0');
        }

		if ($post) {
            if ($editID > 0) 
            {
                $this->{$this->model}->update($editID, $this->{$this->model}->primaryKey, $post['edit']);
            }
			else 
            {
                $post['edit']['sli_createtime'] = time();
                $editID = $this->{$this->model}->insert($post['edit']);
            }
            
            redirect($this->url_edit . $editID);
        }

		$this->template_data['main'] = 'admin/slider/edit';
		$this->template->load('layout/admin/layout',$this->template_data,$data);
	}

    public function delete($pos_id){
        // DELETE RELATED IMAGES
        $this->db->select('posti_image')->where('pos_id',$pos_id);
        $post_images = $this->mpostimage->gets();
        if($post_images)
            foreach ($post_images as $pi)
                @unlink(str_replace(base_url(), '', $pi->posti_image));

        if($file_name)    
            $this->mpostimage->delete($pos_id,'pos_id');

        //DELETE POS_IMAGE
        $post = $this->{$this->model}->get($pos_id);

        if($post){
            @unlink(str_replace(base_url(), '', $post->pos_image));
            //delete record
            $this->{$this->model}->delete($pos_id);    
            //delete post category
            $this->mpostcategory->delete($pos_id,'pos_id');
        }

        echo json_encode(array('success'=>'The image was deleted .'));
    }

    public function delete_image(){
        if($pos_id = $this->input->post('key')){
            $this->db->select('posti_image')->where('posti_id',$pos_id);
            $file_name = $this->mpostimage->get();
            if($file_name){
                @unlink($file_name->posti_image);
                $this->mpostimage->delete($pos_id);
            }
        }
        echo json_encode(array('success'=>'The image was deleted .'));
    }

    public function upload_image($pos_id)
    {
        $config['allowed_types'] = 'gif|jpg|png|jpeg';
        $time = time();
        $patch_upload = 'images/slider/'.date("Y",$time).'/'.date("m",$time).'/';
        $config['upload_path'] = './'.$patch_upload;
        $ext = basename(@$_FILES['pos_name']['name']);
        $ext = explode('.',$ext);
        $ext = end($ext);
        $file_name = $time;
        $rand_code = array();
        $rand_code[0] = rand(0,1000);
        $rand_code[1] = rand(0,1000);
        $config['file_name'] = $file_name.'-hinh-anh-'.$pos_id.'-'.rand(0,1000).'.'.$ext;
        create_dirs($patch_upload.$config['file_name']);
        $this->load->library('upload', $config);
        $this->upload->initialize($config);
        $output = array();
        if (!$this->upload->do_upload('pos_name'))
        {
            // assign response data with error uploaded
            $output = array('error'=>'Error while uploading images. Contact the system administrator');
        }
        else
        {
            // assign response data with file_path of new image was uploaded
            $output = array(
                            'file_path' => base_url().$patch_upload.$config['file_name'],
                            'alt'   => $config['file_name'],
                            'title' =>  $config['file_name'],
                        ); 

            /*
            * update asyn article with primary key equals $pos_id and image path
            * then check the article is contains old image or not
            * yes : delete old image with no error warning
            */
            $this->{$this->model}->update($pos_id, $this->{$this->model}->primaryKey, array('sli_img'=>$output['file_path']));
            if($this->input->post('img_path') !='')
                @unlink($base_url.$this->input->post('img_path'));              
        }

        echo json_encode($output);
    }

    //This func for search by input some related post
    public function do_ajax_search()
    {  
        $result = array();
        $post = $this->input->post();
        // Check $post has datas
        // true:access db and query result then respone to client
        // no:return null;
        if($post && $post['q'] != '' && $post['pos_id'] > 0)
        {
            $this->db->select('post.pos_id,post.pos_title')
                    ->where('post.pos_code like','%'.str_replace(' ', '%', strtolower($post['q'])).'%')
                    ->limit(20);    
            $result = $this->{$this->model}->gets();
        }
        echo json_encode($result);
    }
}

/* End of file Playground.php */
/* Location: ./application/controllers/playground.php */